package com.itheima.controller;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.domain.User;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@RestController
//一级url路径
@RequestMapping("/json")
public class JsonController {


    //响应普通的字符串
    @RequestMapping("/test1")
    public void test1(HttpServletResponse response)throws Exception{
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write("合肥");
    }

//    2.第二种格式
        @RequestMapping(value = "/test2",produces = "text/html;charset=utf-8")
        @ResponseBody//阻止页面跳转，实现页面写入数据
        public String test2()throws Exception{
            return "上海";
        }
        //3.响应一个user对象  为json
        @RequestMapping("/test3")
        public void test3(HttpServletResponse response)throws Exception{
            User u = new User();
            u.setUsername("admin");
            u.setAge(18);
            String json = new ObjectMapper().writeValueAsString(u);
            response.getWriter().write(json);
        }

        //4.第二种 自动转换json
        @RequestMapping(value = "/test4")
        @ResponseBody//将对象转换成json格式数据
        public User test4()throws Exception{
            User u = new User();
            u.setUsername("admin");
            u.setAge(18);
            //直接返回u
            return u;
        }


        //取出cookieValue
    @RequestMapping("/test5")
    @ResponseBody//将对象转换成json格式数据
    public Map test5()throws Exception{
        User u=new User();
        u.setUsername("admin");
        u.setAge(18);

        Map map=new HashMap();
        map.put("user",u);
        //将User对象转换成json字符串
        // String json = new ObjectMapper().writeValueAsString(u);
        return map;
    }
//    @CookieValue("usename") String username, @CookieValue("pwd") String password
}
